<?php
// 仅当会话尚未启动时调用 session_start()
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户是否为读者角色
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'reader') {
    header('Location: http://localhost/Library_management_system/index.php');
    exit();
}

try {
    $pdo = new PDO('mysql:host=localhost;dbname=library', 'root', '123456');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("数据库连接失败: " . $e->getMessage());
}

// 获取当前登录用户的ID
$user_id = $_SESSION['u_No'];

// 检查用户是否被冻结
$stmt = $pdo->prepare('SELECT state FROM users WHERE u_No = ?');
$stmt->execute([$user_id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// 如果用户被冻结，显示错误消息并阻止发表评论
if ($user['state'] === '冻结') {
    echo "您的账户已被冻结，无法发表评论。";
    exit();
}

// 处理评论提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $re_id = $_POST['Re_id'];  // 获取客户端生成的 Re_ID
    $book_id = $_POST['book_id'];  // 获取图书ID（字符类型）
    $content = $_POST['content'];
    $rating = $_POST['rating'];  // 获取评分
    $comment_date = date('Y-m-d H:i:s');

    // 插入评论到数据库
    $stmt = $pdo->prepare('INSERT INTO bookcomment (Re_ID, u_No, book_No, Re_pre, Re_score) VALUES (?, ?, ?, ?, ?)');
    $stmt->execute([$re_id, $user_id, $book_id, $content, $rating]);
    echo "评论成功！";
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发表评论</title>
    <style>
        .stars {
            display: inline-block;
            font-size: 30px;
            color: #ddd;
        }
        .stars .star {
            cursor: pointer;
        }
        .stars .filled {
            color: gold;
        }
    </style>
</head>
<body>
    <h2>发表评论</h2>

    <!-- 评论表单 -->
    <form method="POST">
        <label for="Re_id">评论ID:</label>
        <!-- 隐藏的 Re_id 字段，客户端生成 -->
        <input type="hidden" name="Re_id" id="Re_id" value=""><br><br>

        <label for="book_id">选择图书ID:</label>
        <!-- 修改为文本框以接受字符类型的图书ID -->
        <input type="text" name="book_id" required><br><br>

        <label for="content">评论内容:</label><br>
        <textarea name="content" required></textarea><br><br>

        <label for="rating">评分:</label><br>
        <div class="stars">
            <span class="star" data-value="1">&#9733;</span>
            <span class="star" data-value="2">&#9733;</span>
            <span class="star" data-value="3">&#9733;</span>
            <span class="star" data-value="4">&#9733;</span>
            <span class="star" data-value="5">&#9733;</span>
        </div>
        <input type="hidden" name="rating" value="0" required> <!-- 隐藏的评分字段 -->
        <br><br>
        <button type="submit">提交评论</button>
    </form>

    <script>
        // 星星评分交互
        const stars = document.querySelectorAll('.star');
        const ratingInput = document.querySelector('input[name="rating"]');

        stars.forEach(star => {
            star.addEventListener('mouseover', () => {
                const value = star.getAttribute('data-value');
                fillStars(value);
            });

            star.addEventListener('mouseout', () => {
                const currentRating = ratingInput.value;
                fillStars(currentRating);
            });

            star.addEventListener('click', () => {
                const value = star.getAttribute('data-value');
                ratingInput.value = value; // 将评分值填入隐藏字段
                fillStars(value);
            });
        });

        // 填充星星
        function fillStars(rating) {
            stars.forEach(star => {
                const value = star.getAttribute('data-value');
                if (value <= rating) {
                    star.classList.add('filled');
                } else {
                    star.classList.remove('filled');
                }
            });
        }

        // 生成唯一的 Re_ID（基于当前时间戳，限制为后10位）
        document.getElementById('Re_id').value = 'Re_' + Date.now().toString().slice(-10);
    </script>
</body>
</html>
